/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if (!head)return head;
        ListNode* p = head;
        ListNode* smallHead = new ListNode(0);
        ListNode* bigHead = new ListNode(0);
        ListNode* small = smallHead;
        ListNode* big = bigHead;
        while (p) {
            if (p->val < x) {
                small->next = p;
                small = small->next;
            }
            else {
                big->next = p;
                big = big->next;
            }
            p = p->next;
        }
        big->next = nullptr;
        small->next = bigHead->next;
        return smallHead->next;
    }
};